package ru.housewife.service.eatingmenus;

import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.form.DayMenuForm;
import ru.housewife.form.EatingMenuForm;
import ru.housewife.model.DayMenu;
import ru.housewife.model.EatingMenu;

/**
 * saves new eating menu
 *
 * @author Alexander Troshanin
 */
public class AddNewEatingMenu implements HibernateAction<EatingMenu> {

    private EatingMenuForm eatingMenuForm;

    public AddNewEatingMenu(EatingMenuForm eatingMenuForm) {
        this.eatingMenuForm = eatingMenuForm;
    }

    @Override
    public EatingMenu execute(Session session) {
        DayMenuForm dayMenuForm = eatingMenuForm.getDayMenu();
        DayMenu dayMenu = (DayMenu) session.get(DayMenu.class, dayMenuForm.getId());
        if (dayMenu == null) {
            return null;
        }

        EatingMenu eatingMenu = new EatingMenu();
        eatingMenu.setEatingType(eatingMenuForm.getEatingType());
        eatingMenu.setDayMenu(dayMenu);

        session.save(eatingMenu);
        eatingMenuForm.setId(eatingMenu.getId());
        dayMenuForm.addEatingMenu(new EatingMenuForm(dayMenuForm, eatingMenu));

        // todo: check whether it is necessary to add: dayMenu.getEatingMenus().add(eatingMenu); session.save(dayMenu);

        return eatingMenu;
    }
}
